﻿Imports System.Collections.ObjectModel   


Class CMBench


'Estas variables se ponen de forma global para igualar el rendimiento en memoria que tienen excel.
'Advertencia: se debe tener un estricto control para sincronizar la interface gráfica con la respectiva lista de datos.

Private lstRegistrosBench     As new ObservableCollection(Of CTBench)
Private lstDatosInstrumentos  As new List(Of CTInstrumentoDatos) 
Private lstCvesDecalog        As  IEnumerable 

    Public Sub New()               
     
        Dim idRegBitGral    As Integer     
        Dim idError         as Integer 
        Dim negocio         As New CBenchServicio ()

        idRegBitGral = CUtileria.GrabarBitacora ("CargaBENCH", "constructor", "Inicio")   

        InitializeComponent()
        Mouse.OverrideCursor = Nothing              
        Dim sMsgError As String = ""         
        If CargarInstrumentos(sMsgError) = false then
           idError = CUtileria.GrabarBitacora("CargaBENCH", "constructor","No se ha podido cargar los instrumentos debido a: " & sMsgError)
           CUtileria.CompletarRegBitacora (idError)     
           MessageBox.Show("No se ha podido cargar los instrumentos debido a: " & sMsgError, "Carga de instrumentos", MessageBoxButton.OK,MessageBoxImage.Error) 
        End If


        lstCvesDecalog = negocio.obtenerCvesBenchDecalog ()
                             
        CUtileria.CompletarRegBitacora (idRegBitGral ) 

    End Sub

   
Private Sub grdDatosBench_CellEditEnding(ByVal sender As System.Object , ByVal e As System.Windows.Controls.DataGridCellEditEndingEventArgs) Handles grdDatosBench.CellEditEnding


  Dim negocioBench As New CBenchServicio ()


  Dim col         As Integer 
  Dim reg         As Integer      
  Dim rowData     as DataGridRow
  Dim cellContent As Object

  Dim cellContentTV      As Object
  Dim cellContentEmisora As Object
  Dim cellContentSerie   As Object

   
   If e.EditAction = DataGridEditAction.Commit then
          
      If not sender.CurrentItem is Nothing then

            
                col   =  e.Column.DisplayIndex 
                reg   =  e.Row.GetIndex        
             rowData  = Me.grdDatosBench.ItemContainerGenerator.ContainerFromIndex(reg)                                                                
       
       Select Case col

          Case 0

                cellContent   = Me.grdDatosBench.Columns(col).GetCellContent(rowData)   'contenido de la celda actual

                Dim cellCodigoDecalog As TextBlock =  grdDatosBench.Columns(5).GetCellContent(rowData) 'Código Decalog
                Dim cellBenchDecalog  As TextBlock =  grdDatosBench.Columns(8).GetCellContent(rowData) 'Bench Decalog

                If  cellContent.Text.Trim.Length >= 3  then
                     cellCodigoDecalog.Text  = "BMK" & cellContent.Text.Substring ( (cellContent.Text.Length - 3),3) 

                ElseIf cellContent.Text.Trim.Length = 2 then 
                     cellCodigoDecalog.Text  = "BMK" & cellContent.Text.Substring ( (cellContent.Text.Length - 2),2) 

                ElseIf cellContent.Text.Trim.Length = 1 then
                     cellCodigoDecalog.Text  = "BMK" & cellContent.Text.Substring ( (cellContent.Text.Length - 1),1) 
                End If
 
      
              ' cellBenchDecalog.Text = negocioBench.obtenerCveBenchDecalog (cellContent.Text)                                        
                   

               lstRegistrosBench.Item (reg).CodigoDecalog  = cellCodigoDecalog.Text
               lstRegistrosBench.Item (reg).CveBench       = cellBenchDecalog.Text

         Case 1,2,3

              Dim cellInstrumento As TextBlock =  grdDatosBench.Columns(6).GetCellContent(rowData) 'instrumento
              Dim cellNumInstrumento As TextBlock =  grdDatosBench.Columns(7).GetCellContent(rowData) 'instrumento

              cellContentTV      =  Me.grdDatosBench.Columns(1).GetCellContent(rowData)   
              cellContentEmisora =  Me.grdDatosBench.Columns(2).GetCellContent(rowData)   
              cellContentSerie   =  Me.grdDatosBench.Columns(3).GetCellContent(rowData)  



              If not (cellContentTV.text.trim.Equals("") and cellContentEmisora.text.trim.Equals("") and cellContentSerie.text.trim.Equals("")) then 
                 cellInstrumento.Text = cellContentTV.text & "_" & cellContentEmisora.text & "_" & cellContentSerie.text
                 lstRegistrosBench.Item (reg).Instrumento = cellInstrumento.Text
              End If
                                          

              'Se obtiene el número de instrumento              
              Dim vNumInst = From instrumento in lstDatosInstrumentos
                            Where instrumento.Sh_Nam = cellInstrumento.Text.Trim ()
                            Select instrumento.NumInst 
                    

              If vNumInst.Count = 1 then 
                 cellNumInstrumento.Text = IIf(IsNumeric(vNumInst(0)),vNumInst(0),"")                 
              Else              
                 cellNumInstrumento.Text = ""
              End If
              lstRegistrosBench.Item (reg).NumInstrumento = cellNumInstrumento.Text
              
         Case else


       End Select


      End If

     grdDatosBench.UpdateLayout ()

   End If

End Sub


Private Sub grdDatosBench_MouseRightButtonUp(ByVal sender As System.Object , ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles grdDatosBench.MouseRightButtonUp

 Dim objDepend As DependencyObject = e.OriginalSource 
 Dim celda As DataGridCell = Nothing 

 Dim iReg As Integer = -1
   
  Me.grdDatosBench.ContextMenu = Nothing  
  While not objDepend is Nothing 

        If objDepend.GetType().Name = "DataGridCell" then 
           celda = objDepend           
           
           If celda.IsSelected = false  then               
               Me.grdDatosBench.UnselectAllCells ()                                                                                                                                                                                                                              
           End If              
                                      
           celda.Focus ()                       
           celda.IsSelected = True            

           Dim col As Integer = Me.grdDatosBench.CurrentCell.Column.DisplayIndex   

           If col <=4 then 
             Me.grdDatosBench.ContextMenu = AgregarMenuContextual ()
           end if
                                             
           Exit While 
        End If

       objDepend = VisualTreeHelper.GetParent (objDepend)  
               
  End While

End Sub


Private Function  AgregarMenuContextual() As ContextMenu 
  Dim miMenuContextual        As New ContextMenu
  Dim mnuEliminar             As new System.Windows.Controls.MenuItem 
  Dim mnuAgregar              As new System.Windows.Controls.MenuItem

  Dim mnuPegar                As New System.Windows.Controls.MenuItem


 
 mnuEliminar.Header = "Eliminar registro(s)"
 miMenuContextual.Items.Add(mnuEliminar)
 AddHandler mnuEliminar.Click,AddressOf  mnuEliminarReg_click


 mnuAgregar.Header = "Agregar registro"  
 miMenuContextual.Items.Add(mnuAgregar)
 AddHandler mnuAgregar.Click,AddressOf  mnuAgregarReg_click



mnuPegar.Header = "Pegar"  
miMenuContextual.Items.Add(mnuPegar)
AddHandler mnuPegar.Click,AddressOf  mnuPegar_click 

 

 Return miMenuContextual 

End Function
 

Public Sub mnuEliminarReg_click()
  
Try
    BorraRegistrosSeleccionados(Me.grdDatosBench)
Catch ex As Exception
            MessageBox.Show("Error TI500. Error al intentar eliminar los registros seleccionados: " & ex.Message, "Carga Bench", MessageBoxButton.OK, MessageBoxImage.Error)
End Try
  
End Sub


Private Sub BorraRegistrosSeleccionados(ByRef gridDeDatos As DataGrid) 

Dim lstAux As New List(Of CTBench)
Dim rowAux As Integer = -1

Try
      For each celda As DataGridCellInfo in gridDeDatos.SelectedCells            
          Dim col As Integer = celda.Column.DisplayIndex   
          Dim row As Integer = gridDeDatos.Items.IndexOf  (CType(celda.Item,CTBench))
           
          If row <> rowAux then 
             rowAux = row 
             lstAux.Add (lstRegistrosBench(row))
          End If                                              
       Next

       For Each registro As CTBench In lstAux 
            lstRegistrosBench.Remove(registro)                
       Next              

       grdDatosBench.ItemsSource = lstRegistrosBench 
       grdDatosBench.Items.Refresh () 

Catch ex As Exception
    Throw ex    
End Try


End Sub


Public Sub mnuAgregarReg_click()

Dim iReg As Integer = -1

If Not Me.grdDatosBench.CurrentCell.Item is Nothing then 
     iReg  =  Me.grdDatosBench.Items.IndexOf(CType(Me.grdDatosBench.CurrentCell.Item,CTBench))      
End If


If iReg >=0 then 
   lstRegistrosBench.Insert (iReg,New CTBench ())
   Me.grdDatosBench.Items.Refresh ()
End If
 
End Sub


Private Sub seleccionarcelda(ByRef gridDeDatos As DataGrid, ByVal indexRow As Integer, ByVal indexCol As Integer)
  
Dim row as DataGridRow  = gridDeDatos.ItemContainerGenerator.ContainerFromIndex(indexRow)
Dim cellContent As TextBlock = gridDeDatos.Columns(indexCol).GetCellContent(row)     


  Dim objDepend As DependencyObject = cellContent
  Dim celda As DataGridCell = Nothing 


   While not objDepend is Nothing 

        If objDepend.GetType().Name = "DataGridCell" then 
           celda = objDepend           
           
           If celda.IsSelected = false  then                
               celda.IsSelected = True                  
               celda.Focus ()
               Exit While                
           End If
                                           
        End If

       objDepend = VisualTreeHelper.GetParent (objDepend)   
  End While

End Sub


Private Sub mnuPegar_click(sender As Object, e As RoutedEventArgs)
 Try
   Mouse.OverrideCursor = Cursors.Wait
        pegarDatos(Me.grdDatosBench)          
     Mouse.OverrideCursor = Nothing   
 Catch ex As Exception
   Mouse.OverrideCursor = Nothing   
            MessageBox.Show("Error TI500. " & ex.Message, "Pegar celdas", MessageBoxButton.OK, MessageBoxImage.Exclamation)
 End Try
   
End Sub 

        
Private Sub pegarDatos(ByRef gridDeDatos As DataGrid)

Dim datos As CDatosEnFormatoX 

datos = CUtileria.ObtenerDatosClipboard (vblf ,vbTab)

'1) Validaciones: obtener información del portapapeles

   If datos.Datos.length = 0 then 
      Exit sub
   End If


  If datos is Nothing then 
     MessageBox.Show ("No se pudo copiar los datos") 
     gridDeDatos.CancelEdit (DataGridEditingUnit.Cell)         
     Exit Sub 
  End If

'2) Validaciones: compatibilidad  

   Dim colTot As Integer = 5   'gridDeDatos.Columns.Count    
   Dim rowTot As Integer = gridDeDatos.Items.Count   
  
   Dim colActual As Integer = gridDeDatos.SelectedCells.First.Column.DisplayIndex   
   Dim rowActual As Integer = gridDeDatos.Items.IndexOf  (CType(gridDeDatos.SelectedCells.First.Item,CTBench ))


    'Validar renglones
      
     If datos.NumeroRenglones  > ((rowTot - (rowActual + 1)) + 1)  then 
        MessageBox.Show ("No coinciden las dimensiones de datos a pegar (R)") 
         gridDeDatos.CancelEdit (DataGridEditingUnit.Cell)         
        Exit sub        
     End If

     If datos.NumeroColumnas.Max   > ((colTot - (colActual + 1)) + 1 )  then 
        MessageBox.Show ("No coinciden las dimensiones de datos a pegar (C)")         
        gridDeDatos.CancelEdit (DataGridEditingUnit.Cell)         
        Exit sub
     End If

  '2) Realizar copiado  

     Dim i As Integer = 0
 

     Dim coontador As Integer = 0

     Dim limRow As Integer = (rowActual +  (datos.NumeroRenglones - 1)) 
     Dim limCol As Integer = (colActual +  (datos.NumeroColumnas.Max -1))


     gridDeDatos.UnselectAllCells()


     Try
    

       Dim j As Integer = 0
       For i = rowActual to limRow       
           
            Dim row as DataGridRow  = gridDeDatos.ItemContainerGenerator.ContainerFromIndex(i)
                                     
            For j= colActual to limCol
                 If datos.Datos(i-rowActual)(j-colActual) <> vbLf and  (Not CType(datos.Datos(i-rowActual)(j-colActual),String).Trim ().Equals ("") ) then                
                     Dim cellContent As TextBlock = gridDeDatos.Columns(j).GetCellContent(row)         
                     lstRegistrosBench(i)(j) = datos.Datos(i-rowActual)(j-colActual).ToString.Trim ()                             
                     cellContent.Text = datos.Datos(i-rowActual)(j-colActual).ToString.Trim ()                             
                 End If                 
            Next
                 
        Next
            
            
          For i = rowActual to limRow                                
              ProcesarDatos(gridDeDatos,i)       
          Next
                           

     Catch ex As Exception

         gridDeDatos.Items.Refresh ()          
         Throw New Exception ("No se pudo terminar de copiar los datos debido a que no coinciden con el formato especificado para cada celda",ex)                  
     
     End Try


End Sub


Private Sub ProcesarDatos(ByRef gridDeDatos As DataGrid,ByVal i As Integer, Optional ByVal  h As Integer = -1)

            Dim row             as DataGridRow  = gridDeDatos.ItemContainerGenerator.ContainerFromIndex(i)            
            Dim   Valoractual   As String    = "" 
            Dim cellContent     As TextBlock  
       
          


            Dim modalidad As Integer 
            Dim j As Integer 


            If h = -1 then 
               modalidad = 0  'Todo el registro
            Else
               modalidad = 1 'Solo Una Columana
            End If

              
            If modalidad = 0  or (modalidad =1 and h = 0) then 
    
                  j = 5
                
                  cellContent  = gridDeDatos.Columns(j).GetCellContent(row)         
                
                  Valoractual   = lstRegistrosBench(i)(0)
             

                  If  Valoractual.Length >= 3  then
                       lstRegistrosBench(i)(j)  = "BMK" & Valoractual.Substring ( (Valoractual.Length - 3),3) 

                  ElseIf Valoractual.Length = 2 then 
                       lstRegistrosBench(i)(j) = "BMK" & Valoractual.Substring ( (Valoractual.Length - 2),2) 

                  ElseIf Valoractual.Length = 1 then
                       lstRegistrosBench(i)(j) = "BMK" & Valoractual.Substring ( (Valoractual.Length - 1),1) 

                  ElseIf  Valoractual.Length = 0
                        lstRegistrosBench(i)(j) = "" 
                        
                  End If
 
                  cellContent.Text = lstRegistrosBench(i)(j)

              End If  





             If modalidad = 0  or (modalidad =1 and (h = 1 or h = 2 or h = 3) ) then 
            
                j = 6

                  Valoractual = ""
                  cellContent  = gridDeDatos.Columns(j).GetCellContent(row)

                  Valoractual = lstRegistrosBench(i)(1) & "_" & lstRegistrosBench(i)(2) & "_" & lstRegistrosBench(i)(3)
                  lstRegistrosBench(i)(j) = Valoractual 
                  cellContent.Text = Valoractual 

               End If



               If modalidad = 0  or (modalidad =1 and (h = 1 or h = 2 or h = 3)) then             

                      j = 7

                      Valoractual = ""
                      cellContent  = gridDeDatos.Columns(j).GetCellContent(row)
              
                       Dim vNumInst = From instrumento in lstDatosInstrumentos
                                      Where instrumento.Sh_Nam = lstRegistrosBench(i)(6)
                                     Select instrumento.NumInst 
                    

                      If vNumInst.Count = 1 then 
                         Valoractual = If(IsNumeric(vNumInst(0)),vNumInst(0),"")                 
                      Else              
                         Valoractual = ""
                      End If
             
                      lstRegistrosBench(i)(j) = Valoractual
                       cellContent.Text = Valoractual 

                End If



               If modalidad = 0  or (modalidad =1 and h = 0) then                         
                        j = 8

                      Valoractual = ""
                      cellContent  = gridDeDatos.Columns(j).GetCellContent(row)
              
                       Dim vCveDlg = From clavesdecalog in lstCvesDecalog 
                                     Where clavesdecalog("NOM_BENCH_RGOS") = lstRegistrosBench(i)(0)
                                     Select clavesdecalog("CVE_BENCH_DECALOG")
                    

                      If vCveDlg.Count = 1 then 
                         Valoractual = If(Not IsDBNull(vCveDlg(0)),vCveDlg(0),"")                 
                      Else              
                         Valoractual = ""
                      End If
             
                      lstRegistrosBench(i)(j) = Valoractual
                      cellContent.Text = Valoractual 

              End If

End Sub







#Region "ACCIONES"


    Private Sub btnAgregarRegistro_Click(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs) Handles btnAgregarRegistro.Click
         Try
           AgregarRegistro ()
         Catch ex As Exception
           MessageBox.Show("Error TI500. " & ex.Message, "Insertar registro", MessageBoxButton.OK, MessageBoxImage.Exclamation)
         End Try
        
    End Sub


    Private Sub btnEliminaRegistro_Click(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs) Handles btnEliminaRegistro.Click
          Dim registros As ObservableCollection(Of CTBench ) = grdDatosBench.ItemsSource
          Dim regEliminar As New ObservableCollection(Of CTBench )
          Dim regtAgregado As New CTBench ()
          Dim regRecorrido As New CTBench 


        Mouse.OverrideCursor =  Cursors.Wait  

        If grdDatosBench.SelectedCells.Count > 0 Then
            For Each celda As DataGridCellInfo In grdDatosBench.SelectedCells
                regEliminar.Add(CType(celda.Item, CTBench ))
            Next

            For Each T As CTBench   In regEliminar 
                registros.Remove(T)
            Next

            grdDatosBench.UpdateLayout()
        
        End If

        ValidaCantidadDatos()

        Mouse.OverrideCursor =  Nothing 
    
    End Sub


    Private Sub btnInsertarRegistros_Click(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs) Handles btnInsertarRegistros.Click
              
          Dim msgBorrar As MessageBoxResult 

           '1. Limpiar registros
          If  grdDatosBench.Items.Count  > 0 then 

              msgBorrar = MessageBox.Show ("La infomación actual será eliminar, desea continuar con la inserción de datos","Insertar registros Bench",MessageBoxButton.OKCancel,MessageBoxImage.Question )  
              If msgBorrar = MessageBoxResult.Cancel then 
                 Exit sub
              End If
              
              Mouse.OverrideCursor =  Cursors.Wait  
              lstRegistrosBench.Clear 
              grdDatosBench.Items.Refresh  
              Mouse.OverrideCursor =  NOTHING
          End If
    
          Mouse.OverrideCursor =  Cursors.Wait  
          
          Try
             InertarRegistros(grdDatosBench)
          Catch ex As Exception
               lstRegistrosBench.Clear 
               grdDatosBench.Items.Refresh  
              Mouse.OverrideCursor =  NOTHING
             MessageBox.Show (ex.Message,"Inserción de datos en Bench",MessageBoxButton.OK,MessageBoxImage.Exclamation)              
          End Try
           Mouse.OverrideCursor =  NOTHING   







    End Sub


    Private Sub btnCargarDecalog_Click(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs ) Handles btnCargarDecalog.Click 

        Dim negocioBench   as New CBenchServicio ()
        Dim sMsgError      as String = ""
        Dim regsIncompleto as Integer = 0



         Dim idRegBitGral    as Integer     
         Dim idError         as Integer 
 
 
         idRegBitGral = CUtileria.GrabarBitacora ("CargaBENCH", "CargarDecalog", "Inicio")  


        If lstRegistrosBench.Count > 0 then 

          If ValidarDatosEntrada(regsIncompleto) = True then   

                If BuscarValoresDesconocidos () = False then 
                   If MessageBox.Show("Existen valores no identificados para la clave Bench en Decalog, " & _
                   "¿desea continuar con la carga a Decalog?" ,"Carga a Decalog", MessageBoxButton.OKCancel,MessageBoxImage.Exclamation) = MessageBoxResult.OK then 
                         
                      if negocioBench.GrabarArchivo (lstRegistrosBench,sMsgError) = True then   
                         MessageBox.Show ("El archivo ha sido generado", "Carga Decalog",MessageBoxButton.OK,MessageBoxImage.Information)                
                         negocioBench.EjecutarProceso  
                      else
                         idError = CUtileria.GrabarBitacora ("CargaBENCH", "CargarDecalog", "El archivo no ha sido generado debido a :" & sMsgError)
                         CUtileria.CompletarRegBitacora (idError) 
                         MessageBox.Show ("El archivo no ha sido generado debido a :" & sMsgError , "Carga Decalog",MessageBoxButton.OK,MessageBoxImage.Information)                
                      End If

                   End If
   
                else

                   If negocioBench.GrabarArchivo (lstRegistrosBench,sMsgError) = True then 
                      MessageBox.Show ("El archivo ha sido generado", "Carga Decalog",MessageBoxButton.OK,MessageBoxImage.Information)                
                      negocioBench.EjecutarProceso ()
                   else
                       idError = CUtileria.GrabarBitacora ("CargaBENCH", "CargarDecalog", "El archivo no ha sido generado debido a :" & sMsgError)
                       CUtileria.CompletarRegBitacora (idError) 
                       MessageBox.Show ("El archivo no ha sido generado debido a :" & sMsgError , "Carga Decalog",MessageBoxButton.OK,MessageBoxImage.Information)                
                   End If
        
                End If


           else
             MessageBox.Show("Existen " & regsIncompleto & " registros incompletos, es necesarios completarlos. ", "Carga Decalog",MessageBoxButton.OK,MessageBoxImage.Exclamation )  
           End If

        else
            MessageBox.Show("No existe información para enviar a Decalog. ", "Carga Decalog",MessageBoxButton.OK,MessageBoxImage.Information  )
        End If


        CUtileria.CompletarRegBitacora (idRegBitGral)

End Sub

    Private Sub btnLimpiar_Click(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs ) Handles btnlIMPIAR.Click  

           

           
          If  grdDatosBench.Items.Count  > 0 then 

               If MessageBox.Show ("¿Esta seguro que desea borrar toda la información capturada?","Borrar información",MessageBoxButton.YesNo,MessageBoxImage.Question) = MessageBoxResult.No then 
                  Exit sub
               End If
                          
              Mouse.OverrideCursor =  Cursors.Wait  
                lstRegistrosBench.Clear 
                grdDatosBench.Items.Refresh  
              Mouse.OverrideCursor =  NOTHING
          End If
    
      
   
    End Sub

#End Region



 #Region "FUNCIONES RELACIONADAS"

        Private Function ObtenerCelda(ByRef miDataGrid As DataGrid, ByVal indexRow As Integer, ByVal indexCol As Integer) As DataGridCell
            Try
                Dim row As DataGridRow = miDataGrid.ItemContainerGenerator.ContainerFromIndex(indexRow)
                Dim cellContent As Object = miDataGrid.Columns(indexCol).GetCellContent(row)

                Dim objDepend As DependencyObject = cellContent
                Dim celda As DataGridCell = Nothing

                While Not objDepend Is Nothing

                    If objDepend.GetType().Name = "DataGridCell" Then
                        celda = objDepend
                        Return celda
                    End If
                    objDepend = VisualTreeHelper.GetParent(objDepend)
                End While
            Catch ex As Exception
                Throw ex
            End Try

            Return Nothing
        End Function

        Private Sub ValidaCantidadDatos()
            If grdDatosBench.Items.Count > 0 Then            
                btnEliminaRegistro.IsEnabled = True
            Else
           
                btnEliminaRegistro.IsEnabled = False
            End If
         End Sub

        Private Sub AgregarRegistro()
            grdDatosBench.UnselectAllCells()
            grdDatosBench.UpdateLayout()


            If Not grdDatosBench.ItemsSource is Nothing then 
               lstRegistrosBench = grdDatosBench.ItemsSource
            End If

        
            lstRegistrosBench.Add(New CTBench )

            grdDatosBench.ItemsSource = lstRegistrosBench 


            grdDatosBench.ScrollIntoView(grdDatosBench.Items(grdDatosBench.Items.Count - 1))
            grdDatosBench.UpdateLayout()

            Dim celda As DataGridCell = ObtenerCelda(grdDatosBench, grdDatosBench.Items.Count - 1, 0)
            If Not celda Is Nothing Then
                celda.Focus()                
                celda.IsSelected = True
            End If

            ValidaCantidadDatos()


    End Sub

        Private Sub InertarRegistros(ByRef gridDeDatos As DataGrid)
            Dim datos As CDatosEnFormatoX 

            datos = CUtileria.ObtenerDatosClipboard (vblf ,vbTab)

            '1) Validaciones: obtener información del portapapeles

               If datos.Datos.length = 0 then 
                  Exit sub
               End If


              If datos is Nothing then 
                 MessageBox.Show ("No se pudo copiar los datos") 
                 gridDeDatos.CancelEdit (DataGridEditingUnit.Cell)         
                 Exit Sub 
              End If


             Dim i As Integer = 0
             
             
             For i  = 1 to  datos.NumeroRenglones 
                AgregarRegistro()
             Next



            '2) Validaciones: compatibilidad  

               Dim colTot As Integer = 5   'gridDeDatos.Columns.Count    
               Dim rowTot As Integer = gridDeDatos.Items.Count   
  
               Dim colActual As Integer = 0
               Dim rowActual As Integer = 0


                'Validar renglones
      
                 If datos.NumeroRenglones  > ((rowTot - (rowActual + 1)) + 1)  then 
                    MessageBox.Show ("No coinciden las dimensiones de datos a pegar (R)") 
                     gridDeDatos.CancelEdit (DataGridEditingUnit.Cell)         
                    Exit sub        
                 End If

                 If datos.NumeroColumnas.Max   > ((colTot - (colActual + 1)) + 1 )  then 
                    MessageBox.Show ("No coinciden las dimensiones de datos a pegar (C)")         
                    gridDeDatos.CancelEdit (DataGridEditingUnit.Cell)         
                    Exit sub
                 End If

              '2) Realizar copiado  

                
                
                
                 i  = 0
                 Dim coontador As Integer = 0

                 Dim limRow As Integer = (rowActual +  (datos.NumeroRenglones - 1)) 
                 Dim limCol As Integer = (colActual +  (datos.NumeroColumnas.Max -1))


                 gridDeDatos.UnselectAllCells()


                 Try
    

                   Dim j As Integer = 0
                   For i = rowActual to limRow       
           
                        Dim row as DataGridRow  = gridDeDatos.ItemContainerGenerator.ContainerFromIndex(i)
                                     
                        For j= colActual to limCol
                             If datos.Datos(i-rowActual)(j-colActual) <> vbLf and  (Not CType(datos.Datos(i-rowActual)(j-colActual),String).Trim ().Equals ("") ) then                
                                 Dim cellContent As TextBlock = gridDeDatos.Columns(j).GetCellContent(row)         
                                 lstRegistrosBench(i)(j) = datos.Datos(i-rowActual)(j-colActual).ToString.Trim ()                             
                                 cellContent.Text = datos.Datos(i-rowActual)(j-colActual).ToString.Trim ()                             
                             End If                 
                        Next
                 
                    Next
            
            
                      For i = rowActual to limRow                                
                          ProcesarDatos(gridDeDatos,i)       
                      Next
                           

                 Catch ex As Exception

                     gridDeDatos.Items.Refresh ()          
                     Throw New Exception ("No se pudo terminar de copiar los datos debido a que no coinciden con el formato especificado para cada celda",ex)                  
     
                 End Try

     
        End Sub





 #End Region







Private Sub BorraDatosSeleccionados(ByRef gridDeDatos As DataGrid) 



Try
      For each celda As DataGridCellInfo in gridDeDatos.SelectedCells            
          Dim col As Integer = celda.Column.DisplayIndex   
                    
          If col <=4 then           
                Dim row As Integer = gridDeDatos.Items.IndexOf  (CType(celda.Item,CTBench))                      
                Dim rowData as DataGridRow  = gridDeDatos.ItemContainerGenerator.ContainerFromIndex(row)
                Dim cellContent As TextBlock = gridDeDatos.Columns(col).GetCellContent(rowData)
          
                cellContent.Text = ""
                lstRegistrosBench (row)(col) =""
                ProcesarDatos(gridDeDatos,row,col )  
          End If

         
                    
       Next
     
Catch ex As Exception
    Throw ex    
End Try


End Sub

Private Sub LimpiarRegistroBench(ByRef registro As CTBench )
Dim i As Integer 

   For i = 0 to CTBench.NUM_PROPIEDADES - 1
       registro(i) = Nothing 
   Next 
End Sub

Public Sub CargarInstrumentosVisual()
   Dim sMsgError As String = "" 
        

   Dim idRegBitGral    as Integer     
   Dim idError         as Integer 
   

   idRegBitGral = CUtileria.GrabarBitacora ("CargaBENCH", "ImpInstrumentos", "Inicio")  


  If CargarInstrumentos(sMsgError) = false then 
     idError = CUtileria.GrabarBitacora ("CargaBENCH", "ImpInstrumentos", "No se ha podido cargar los instrumentos debido a: " & sMsgError)  
     MessageBox.Show("No se ha podido cargar los instrumentos debido a: " & sMsgError, "Carga de instrumentos", MessageBoxButton.OK,MessageBoxImage.Error) 
  Else
    MessageBox.Show("Los instrumentos han sido importados", "Carga de instrumentos", MessageBoxButton.OK,MessageBoxImage.Information)    
  End If

  CUtileria.CompletarRegBitacora (idRegBitGral)

End Sub

Public function CargarInstrumentos(ByRef sMsgError As String) As Boolean 

 Dim negocioBench As New CBenchServicio()      

 Try
    lstDatosInstrumentos = negocioBench.ObtenerValoresInstrumentos ()
    Return true
 Catch ex As Exception
            sMsgError = "Error TI500. " & ex.Message
    Return False 
 End Try
 

End function

Private Function ValidarDatosEntrada(ByRef regsIncompletos As Integer ) As Boolean 

Dim val1 As Byte 
Dim val2 As Byte 
Dim val3 As Byte 
Dim val4 As Byte 
Dim val5 As Byte 


regsIncompletos  = 0

For Each registro As CTBench In lstRegistrosBench 
  
   With registro 

      val1 =  IIf(.BenchControl.Trim.Equals(""),0,1)  
      val2 =  IIf(.TipoValor.Trim.Equals(""),0,1)
      val3 =  IIf(.Emisora.Trim.Equals(""),0,1)
      val4 =  IIf(.Serie.Trim.Equals(""),0,1)
      val5 =  IIf(.Peso.Trim.Equals(""),0,1)

      If (val1 * val2 * val3 * val4 * val5) = 0 then 
         regsIncompletos += 1      
      End If

   End With  

Next

 If regsIncompletos = 0 then 
    Return true
  else
    Return false
 End If


End Function

Private Function BuscarValoresDesconocidos() As Boolean 


  For Each registro As CTBench In lstRegistrosBench
           
    if  registro.CveBench.Equals ("#M/V") or   registro.CveBench.Equals ("#N/A") or registro.CveBench.Equals ("#ERROR") then 
         Return False 
    End If
  Next

  Return True 
End Function

End Class
